package company.permissionsystem.security;


import company.permissionsystem.security.dao.UserDetailsDao;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;

@Component
public class UserDetailsServiceImpl implements UserDetailsService {

    @Resource
    private UserDetailsDao userDetailsDao;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        /**
         *  加载用户的基本信息
         * */
        SystemUserDetails systemUserDetails = userDetailsDao.findUserByName(username);

        System.out.println(systemUserDetails.getUsername());
        System.out.println(systemUserDetails.getPassword());
        /**
         *  加载用户的角色
         * */
        String role = userDetailsDao.findRoleNameByUserName(username);

        System.out.println("角色" + role);

        /**
         *  通过用户列表加载用户的资源权限列表
         * */
        List<String> authorties = userDetailsDao.findAuthortyByUserName(username);

        //角色是一个特殊的权限，ROLE_前缀
        StringBuffer sys_role = new StringBuffer(role);
        sys_role.insert(0, "ROLE_");
        authorties.add(sys_role.toString());

        System.out.println("拥有权限资源" + authorties.toString());

        systemUserDetails.setAuthorities(
                AuthorityUtils.commaSeparatedStringToAuthorityList(
                        String.join(",", authorties)
                )
        );
        return systemUserDetails;
    }
}
